// 认证中间件
const { AuthError } = require('../utils/customError')

const { verify } = require('jsonwebtoken')
const redis = require('../config/redis')
require('dotenv').config()

const auth = async (ctx, next) => {
  const username = ctx.headers.authorization
  let token
  if (username) {
    // redis 获取 token
    const redisToken = await redis.get(`token:${username}`)
    if (!redisToken) {
      ctx.status = 401
      throw new AuthError('未授权访问')
    }
    token = redisToken
  }
  try {
    ctx.state.user = verify(token, process.env['JWT_SECRET'])
    // 将解码的用户信息挂载到上下文
    await next()
  } catch (err) {
    console.error(err)
    throw new AuthError('无效或过期的令牌')
  }
}

module.exports = auth
